// We want to take in a list and return an array of struct string *

#include <stdio.h>
#include <string.h>
#include <stdlib.h>

void * Malloc( size_t size ) {
  void * toReturn = malloc(size);
  if ( ! toReturn ) {
    perror("malloc");
    exit(1);
  }
  return toReturn;
}

char ** split ( char * phrase, int delim, int * numSub ) {

  int num = 0;
  int maxlen = -1;
  char * iter;

  // Figure out how many different subphrases there are
  iter = phrase;
  while ( 1 ) {
    char * tmp = strchr(iter, delim);
    num ++ ;
    int len;
    if ( ! tmp ) {
      len = strlen(iter);
    }
    else {
      len = (tmp - iter) / sizeof(char);
    }
    if ( len > maxlen ) {
      maxlen = len;
    }
    if ( ! tmp || ! (*(++tmp)) ) {
      break;
    }
    iter =  tmp;
  }

  char ** toReturn = Malloc (num * sizeof(char * ));
  int i;
  iter = phrase;
  for (i = 0; i < num; i++) {
    toReturn[i] = Malloc(maxlen * sizeof(char));
    char * tmp = strchr( iter, delim );
    if ( ! tmp ) {
      strncpy( toReturn[i], iter, maxlen );
    }
    else {
      char val = *tmp;
      strncpy( toReturn[i], iter, (tmp - iter)/sizeof(char) );
      iter = ++ tmp;
    }
  }


  *numSub = num;
  return toReturn;

}

int main() {

  int n;
  char ** ret = split("A.B.CD", '.', &n);

  int i;
  for (i = 0; i < n; i++) {
    printf("%d: %s\n", i+1, ret[i]);
  }

}
  

